package org.example.core.job;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.example.api.ComfyuiApi;
import org.example.core.Service.RedisService;
import org.example.core.Service.UserFundRecordService;
import org.example.core.pojo.ComfyuiTask;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static org.example.core.Service.impl.RedisServiceImpl.TASK_KEY_PREFIX;

@Slf4j
@Component
public class RunTaskJob {
    final static String SPRING_TASK_LOCK_KEY="SPRING_TASK_LOCK_KEY";
    public final static String TASK_RUN_SEMAPHORE="TASK_RUN_SEMAPHORE";
    @Autowired
    ComfyuiApi  comfyuiApi;
    @Autowired
    RedisService redisService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserFundRecordService userFundRecordService;


    public void sentTaskToComfyui(){
        try {
            ComfyuiTask comfyuiTask = redisService.popQueueTask();
            if(comfyuiTask==null){
                return;
            }
            Call<HashMap> hashMapCall = comfyuiApi.addQueueTask(comfyuiTask.getComfyuiRequestDto());
            Response<HashMap> response = hashMapCall.execute();
            if(response.isSuccessful()){
                HashMap data = response.body();
                String promptId=data.get("prompt_id").toString();
                comfyuiTask.setPromptId(promptId);
                stringRedisTemplate.opsForValue().set(TASK_KEY_PREFIX+comfyuiTask.getId(),JSON.toJSONString(comfyuiTask));
                System.out.println("*********************************************comfyuiTask:"+comfyuiTask);
                redisService.addStartTask(promptId,comfyuiTask);
                log.info("sentTaskToComfyui success:{}", comfyuiTask.getPromptId());
            }else {

                String data = response.errorBody().toString();
                log.info("sentTaskToComfyui fail:{}", data);
                //归还冻结积分
                userFundRecordService.freezeReturn(comfyuiTask.getUserId(),comfyuiTask.getSize());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
        }
    }

    @Scheduled(cron = "*/1 * * * * ?")
    public void runTask() throws InterruptedException {
        //获取锁
        RLock lock = redissonClient.getLock(SPRING_TASK_LOCK_KEY);
        //占用锁
        if(lock.tryLock(60, TimeUnit.MINUTES)){
            try {
                if(redisService.hasQueueTask()){
                    RSemaphore semaphore = redissonClient.getSemaphore(TASK_RUN_SEMAPHORE);
                    if(semaphore.tryAcquire()) {
                        sentTaskToComfyui();
                    }
                }
            }finally {
                lock.unlock();
            }
        }
        else {
            log.warn("Failed to acquire lock for task execution.");
        }
        }
}
